<template>
  <page-wrap stay-still back hide-tab contentWrapColor="#fff">
    <view class="aim-item">
      <view class="aim-item-form-wrap">
        <u-form
          class="aim-item-form"
          label-position="top"
          ref="uForm"
          :model="form"
          :error-type="['message']"
        >
          <view class="form-top">
            <view class="form-top-title"
              >{{ intended_id ? "编辑" : "添加" }}求职意向</view
            >
            <view class="form-top-subtitle">{{
              intended_id
                ? "完善求职意向，提升招聘者发现你的机率"
                : "求职意向的不同，推荐的职位也会不同"
            }}</view>
          </view>
          <view
            class="form-item-wrap"
            v-for="(item, index) in formList"
            :key="index"
            @click.capture="handleSelect(item)"
          >
            <u-form-item
              :class="{ pick: item.comp }"
              :label="item.label"
              :label-style="labelStyleObj"
              :prop="item.prop"
              :required="item.required"
            >
              <u-input
                class="form-input"
                v-model="form[item.prop]"
                :disabled="!!item.comp"
                :placeholder="item.inputPlaceholder"
                :clearable="false"
                :type="item.type || 'text'"
              />
              <!-- 下拉选择 -->
              <u-select
                class="form-select"
                v-model="showSelect"
                :list="item.data"
                v-if="item.comp === 'select'"
                @confirm="handleConfirm($event, item)"
              ></u-select>
              <!-- 自定义选择 -->
              <u-popup
                class="form-comp"
                v-model="showRegion"
                mode="bottom"
                z-index="100"
                safe-area-inset-bottom
                v-if="item.comp === 'region'"
              >
                <view class="u-flex u-row-between btn-group">
                  <text class="cancel" @click="showRegion = false">取消</text>
                  <text
                    class="confirm"
                    type="primary"
                    size="medium"
                    @click="showRegion = false"
                    >保存</text
                  >
                </view>
                <scroll-view scroll-y="true" style="height: 50vh">
                  <region-filter
                    limit
                    :form-data="form[item.propVal]"
                    :prop-list="item.propList"
                    @confirm="handleReturn(arguments, index)"
                  ></region-filter>
                </scroll-view>
              </u-popup>
              <u-popup
                class="form-comp"
                v-model="showTrade"
                mode="bottom"
                z-index="100"
                safe-area-inset-bottom
                v-if="item.comp === 'trade'"
              >
                <view class="u-flex u-row-between btn-group">
                  <text class="cancel" @click="showTrade = false">取消</text>
                  <text
                    class="confirm"
                    type="primary"
                    size="medium"
                    @click="showTrade = false"
                    >保存</text
                  >
                </view>
                <scroll-view scroll-y="true" style="height: 50vh">
                  <trade-filter
                    limit
                    :form-data="[item.activeParent, form[item.propVal]]"
                    :prop-list="item.propList"
                    @confirm="handleReturn(arguments, index)"
                  ></trade-filter>
                </scroll-view>
              </u-popup>
              <u-popup
                class="form-comp"
                v-model="showPost"
                mode="bottom"
                z-index="100"
                safe-area-inset-bottom
                v-if="item.comp === 'job'"
              >
                <view class="u-flex u-row-between btn-group">
                  <text class="cancel" @click="showPost = false">取消</text>
                  <text
                    class="confirm"
                    type="primary"
                    size="medium"
                    @click="showPost = false"
                    >保存</text
                  >
                </view>
                <scroll-view scroll-y="true" style="height: 50vh">
                  <job-classify-filter
                    limit
                    :form-data="form[item.propVal]"
                    :prop-list="item.propList"
                    :tradeId="form.tradeid"
                    @confirm="handleReturn(arguments, index)"
                  ></job-classify-filter>
                </scroll-view>
              </u-popup>
            </u-form-item>
          </view>
        </u-form>
      </view>
      <view class="aim-item-opt">
        <u-button
          class="del-btn"
          v-if="intended_id"
          :custom-style="customStyle"
          :hair-line="false"
          @click="handleDelete"
          >删除</u-button
        >
        <u-button
          class="save-btn"
          :custom-style="saveBtnStyle"
          :hair-line="false"
          :loading="loading"
          @click="handleSave"
          >{{ saveBtnText }}</u-button
        >
      </view>
    </view>
  </page-wrap>
</template>

<script>
// import region from '@/utils/region.min';
import { getFileByUrl } from "@/api/index";
import { insertDefault } from "@/utils/handle";
import { resumeTypeList } from "@/utils/data";

import newResumeItem from "@/mixins/newResumeItem";
import {
  getIntendedTradeInfo,
  addIntendedTrade,
  deleteIntendedTrade,
  updateIntendedTrade,
} from "@/api/index";

import RegionFilter from "@/components/RegionFilter";
import TradeFilter from "../../components/TradeFilter";
import JobClassifyFilter from "../components/JobClassifyFilter";
import {
  dealSingleModuleScore,
  saveAndUpdateResearchReport,
} from "@/api/modules/career.js";
import ShareMixin from "@/mixins/share";
export default {
  mixins: [ShareMixin, newResumeItem],
  components: {
    RegionFilter,
    TradeFilter,
    JobClassifyFilter,
  },
  data() {
    return {
      navBarTitle: "完善求职意向",
      personId: uni.getStorageSync("person-id").slice(2) || undefined,
      intended_id: "",
      aimInfo: {},
      form: {},
      showSelect: false,
      showRegion: false,
      showTrade: false,
      showPost: false,
      formList: this.$needTrade
        ? [
            {
              label: "期望行业",
              prop: "tradeName",
              propVal: "tradeid",
              inputPlaceholder: "请选择期望行业",
              comp: "trade",
              show: "showTrade",
              propList: ["tradeid", "tradeName"],
              activeParent: "",
              required: true,
            },
            {
              label: "意向职位",
              prop: "zwname",
              propVal: "zwid",
              inputPlaceholder: "请选择意向职位",
              comp: "job",
              show: "showPost",
              propList: ["zwid", "zwname", "parentid"],
              required: true,
            },
            {
              label: "意向城市",
              prop: "intended_cityName",
              propVal: "intended_city",
              inputPlaceholder: "请选择意向城市",
              comp: "region",
              show: "showRegion",
              propList: ["intended_city", "intended_cityName"],
              required: true,
            },
            {
              label: "期望月薪",
              prop: "min_salary",
              inputPlaceholder: "请输入期望月薪(元)",
              type: "number",
            },
            {
              label: "求职类型",
              prop: "jobtypeName",
              propVal: "jobtype",
              inputPlaceholder: "请选择求职类型",
              comp: "select",
              data: resumeTypeList,
              show: "showSelect",
            },
          ]
        : [
            {
              label: "意向职位",
              prop: "zwname",
              propVal: "zwid",
              inputPlaceholder: "请选择意向职位",
              comp: "job",
              show: "showPost",
              propList: ["zwid", "zwname", "parentid"],
            },
            {
              label: "意向城市",
              prop: "intended_cityName",
              propVal: "intended_city",
              inputPlaceholder: "请选择意向城市",
              comp: "region",
              show: "showRegion",
              propList: ["intended_city", "intended_cityName"],
            },
            {
              label: "期望月薪",
              prop: "min_salary",
              inputPlaceholder: "请输入期望月薪(元)",
              type: "number",
            },
            {
              label: "求职类型",
              prop: "jobtypeName",
              propVal: "jobtype",
              inputPlaceholder: "请选择求职类型",
              comp: "select",
              data: resumeTypeList,
              show: "showSelect",
            },
          ],
      rules: this.$needTrade
        ? {
            tradeName: [
              {
                required: true,
                message: "请选择期望行业",
              },
            ],
            zwname: [
              {
                required: true,
                message: "请选择意向职位",
              },
            ],
            intended_cityName: [
              {
                required: true,
                message: "请选择意向城市",
              },
            ],
          }
        : {
            zwname: [
              {
                required: true,
                message: "请选择意向职位",
              },
            ],
            intended_cityName: [
              {
                required: true,
                message: "请选择意向城市",
              },
            ],
          },
      loading: false,
      customStyle: {
        color: "#555",
        borderColor: "transparent",
        backgroundColor: "#F5F6F7",
      },
      saveBtnStyle: {
        color: "#FFF",
        border: "none",
        borderRadius: "42rpx",
        background: "#F04646",
      },
      labelStyleObj: {
        color: "#666",
      },
      from: "",
      region: [],
      dataObj: {},
      saveBtnText: "完成",
      stepNum: 2,
      jumpUrl: "/pagesSub/newResume/completeResumeSteps/edus",
    };
  },
  watch: {
    aimInfo: {
      handler(val) {
        let postList =
          val.intended_jobs && val.intended_jobs.length
            ? val.intended_jobs[0]
            : {};
        this.form = {
          tradeid: val.tradeid,
          tradeName: val.tradeName,
          zwid: postList.zwid,
          zwname: postList.zwname,
          intended_city: val.intended_city,
          intended_cityName: this.handleRegionName(val.intended_city),
          min_salary: parseInt(val.min_salary),
          max_salary: val.max_salary,
          jobtype: val.jobtype,
          jobtypeName: this.handleJobtypeName(val.jobtype),
        };
      },
      immediate: true,
    },
  },
  onLoad(options) {
    this.intended_id = options.intended_id;
    this.from = options.from;

    if (options.data) {
      let decodedData = decodeURIComponent(options.data);
      let dataObj = JSON.parse(decodedData);
      this.dataObj = dataObj;
      console.log("data-obj", this.dataObj);
      let obj = this.dataObj.complete_info;
      if (obj) {
        let baseInfo = obj.baseInfo;
        let edus = obj.edus;
        if (edus != 2) {
          this.stepNum = 3;
          this.saveBtnText = baseInfo != 2 ? "下一步（2/3）" : "下一步（1/2）";
          this.jumpUrl =
            `/pagesSub/newResume/completeResumeSteps/edus?data=` +
            encodeURIComponent(JSON.stringify(dataObj));
          console.log("进来了", this.jumpUrl);
        } else {
          console.log("进来了2", this.jumpUrl);
          this.jumpUrl = "";
          this.stepNum = 2;
          this.saveBtnText = "完成";
        }
      }
    }
  },
  onShow() {
    this.getIntendedTradeInfo();
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  created() {
    getFileByUrl(
      "https://img3.job1001.com/ypMp/elan/files/region.min.json"
    ).then((res) => {
      this.region = insertDefault(res);
    });
  },
  methods: {
    //编辑单个简历模块上报
    dealSingleModuleScore() {
      const params = {
        personId: this.personId || uni.getStorageSync("person-id").slice(2),
        resumeModule: 3, //简历模块 1:基本信息 2:求职状态 3:求职意向 4:工作经历 5:项目经验 6：自我评价 7：教育背景 8：个人证书 9：技能特长 10：培训经历 11：校园经历 12：奖项荣誉
      };
      dealSingleModuleScore(params);
    },
    handleRegionName(regionId) {
      console.log("regionId", regionId);

      if (regionId) {
        let regionPId = regionId.slice(0, 2) + "0000";
        let regionCId = regionId.slice(0, 4) + "00";
        let regionP = this.region.find((ele) => ele.value === regionPId);
        let regionC = regionP.children.find((ele) => ele.value === regionCId);
        if (regionC.children) {
          let regionF = regionC.children.find((ele) => ele.value === regionId);
          return regionP.label + " - " + regionC.label + "-" + regionF.label;
        } else {
          return regionP.label + " - " + regionC.label;
        }
      } else {
        return "";
      }
    },
    handleJobtypeName(jobtype) {
      if (jobtype) {
        for (let i = 0; i < resumeTypeList.length; i++) {
          if (resumeTypeList[i].value == jobtype) {
            return resumeTypeList[i].label;
          }
        }
      } else {
        return "";
      }
    },
    handleReturn([data, name], index) {
      console.log("handleReturn", [data, name], index);
      if (Array.isArray(name) && Array.isArray(data)) {
        name.forEach((ele, idx) => {
          if (ele == "tradeid") {
            this.$set(this.form, "zwname", "");
          }
          console.log("选择了期望行业");
          this.$set(this.form, ele, data[idx]);
        });
        if (!index) {
          this.$set(this.formList[index], "activeParent", data[2]);
        }
      } else {
        this.$set(this.form, name, data);
      }
      this[this.formList[index].show] = false;
      setTimeout(() => {
        this.$refs.uForm.validate();
      }, 0);
    },
    getIntendedTradeInfo(update) {
      let param = {
        person_id: this.personId,
        intended_id: this.intended_id,
      };
      getIntendedTradeInfo(param).then((res) => {
        if (+res.code === 200) {
          this.aimInfo = res.data;
        }
      });
    },
    handleAvatar() {
      uni.navigateTo({
        url: `/pagesSub/resume/cropper/index?destWidth=${600}&rectWidth=${300}`,
      });
    },
    handleSelect(item) {
      if (item.comp) {
        this[item.show] = true;
      }
    },
    handleConfirm(e, item) {
      if (Array.isArray(e)) {
        this.$set(this.form, item.prop, e[0].label);
        this.$set(this.form, item.propVal, e[0].value);
      } else {
        let time = `${e.year}-${e.month}-${e.day}`;
        this.$set(this.form, item.prop, time);
      }
    },
    handleSave() {
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          if (this.intended_id) {
            this.updateIntendedTrade();
          } else {
            this.addIntendedTradeInfo();
          }
          //修改求职意向更新职途报告状态
          saveAndUpdateResearchReport({
            personId: this.personId,
            rightId: -2,
          });
          uni.setStorageSync("aimUpdated", true);
        } else {
          uni.showToast({ icon: "none", title: "请完善信息后保存" });
        }
      });
    },
    // 添加
    addIntendedTradeInfo() {
      let params = {
        person_id: this.personId,
        param: JSON.stringify(this.form),
      };

      addIntendedTrade(params)
        .then((res) => {
          if (res.code == 200) {
            this.dealSingleModuleScore();
            uni.setStorageSync("resumeUpdated", true); //设置一个标识，在resumeAssesment如果为true才会请求接口
            uni.showToast({
              icon: "none",
              title: "添加成功",
              complete: () => {
                setTimeout( () => {
                  uni.$emit("aimUpdate");
                  uni.$emit("wantJobUpdate"); // 让ai简历诊断的首页更新意向列表  页面：AIResumeDiagnoseNew.vue
                  // uni.navigateBack();
                  if (this.stepNum == 2) {
                    uni.navigateBack(); //返回上一个页面
                  } else {
                    uni.redirectTo({
                      url: this.jumpUrl,
                    });
                  }
                }, 1500);
              },
            });
          } else {
            if (res.status_desc === "不能超过三个") {
              uni.showToast({
                icon: "none",
                title: "最多添加3个求职意向,请前往修改",
              });
              if (this.from == "careerReportJobTips") {
                setTimeout(() => {
                  uni.redirectTo({
                    url: "/pagesSub/newResume/index",
                  });
                }, 1000);
              }
            } else {
              uni.showToast({ icon: "none", title: res.status_desc });
            }
          }
        })
        .catch((err) => {
          console.error(err);
        });
    },

    // 更新
    updateIntendedTrade() {
      let tempObj = { ...this.form };
      tempObj.intended_id = this.intended_id;
      let params = {
        person_id: this.personId,
        param: JSON.stringify(tempObj),
      };

      updateIntendedTrade(params)
        .then((res) => {
          if (res.code == 200) {
            this.dealSingleModuleScore();
            uni.setStorageSync("resumeUpdated", true); //设置一个标识，在resumeAssesment如果为true才会请求接口
            uni.showToast({
              icon: "none",
              title: "更新成功",
              complete() {
                setTimeout(() => {
                  uni.$emit("aimUpdate");
                  uni.$emit("wantJobUpdate");
                  uni.navigateBack();
                }, 1500);
              },
            });
          } else {
            uni.showToast({ icon: "none", title: res.status_desc });
          }
        })
        .catch((err) => {
          console.error(err);
        });
    },
    handleDelete() {
      uni.showModal({
        title: "温馨提示",
        content: `确认删除求职意向？`,
        success: (modalRes) => {
          if (modalRes.confirm) {
            var data = {
              person_id: this.personId,
              intended_id: this.intended_id,
            };
            deleteIntendedTrade(data).then((res) => {
              if (res.code == 200) {
                this.dealSingleModuleScore();
                uni.setStorageSync("resumeUpdated", true); //设置一个标识，在resumeAssesment如果为true才会请求接口
                uni.showToast({
                  icon: "none",
                  title: "删除成功",
                  complete() {
                    setTimeout(() => {
                      uni.$emit("aimUpdate");
                      uni.$emit("wantJobUpdate");
                      uni.navigateBack();
                    }, 1500);
                  },
                });
              } else {
                uni.showToast({ icon: "none", title: res.status_desc });
              }
            });
          }
        },
      });
    },
  },
};
</script>

<style lang="scss">
.aim-item {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 0rpx 0rpx 36rpx;
  box-sizing: border-box;
  background-color: $uni-bg-color;
  .form-top {
    margin-bottom: 58rpx;
    &-title {
      font-size: 48rpx;
      color: #000000;
      font-weight: bold;
      margin-bottom: 16rpx;
    }
    &-subtitle {
      font-size: 26rpx;
      color: #555555;
    }
  }
  .aim-item-form-wrap {
    flex-grow: 1;
    ::v-deep .u-form {
      padding: 32rpx 32rpx 0;
      background: $uni-bg-color;
      border-radius: 24rpx;
      .u-form-item {
        padding: 32rpx 0 12rpx;
        .btn-group {
          padding: 0 24rpx;
          line-height: 102rpx;
          .cancel,
          .confirm {
            padding: 0 16rpx;
          }
        }
        .form-cms {
          ::v-deep .uni-scroll-view-content {
            padding: 0 32rpx 32rpx;
            box-sizing: border-box;
            .title {
              line-height: 90rpx;
              text-align: center;
              font-size: $uni-font-size-lg;
            }
            .u-field {
              padding: 24rpx 0;
            }
            .send-code {
              color: $u-type-primary;
            }
            .confirm-btn {
              margin-top: 44rpx;
            }
          }
        }
      }
    }
  }
  .aim-item-opt {
    position: fixed;
    bottom: 50rpx;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    padding: 0 32rpx;
    width: 100vw;
    z-index: 2;
    .del-btn {
      flex-shrink: 0;
      margin-right: 40rpx;
      width: 180rpx;
      background: #f5f6f7;
      border-radius: 16rpx;
    }
    .save-btn {
      flex-grow: 1;
    }
  }
}
.u-form-item {
  .u-input::v-deep input {
    font-size: $uni-font-size-lg !important;
  }
  ::v-deep .u-form-item__body::after {
    top: 64%;
    margin-top: 0rpx;
    background-image: url($img-base + "career/right-arrow.png?v=1");
    width: 24rpx;
    height: 24rpx;
  }
}
</style>
